import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { isPhone, isEmail } from "@pureadmin/utils";
import {
  getAlarmBehaveListApi,
  createAlarmBehaveApi,
  updateAlarmBehaveApi,
  delAlarmBehaveApi,
  getAlarmBehaveShowApi,
  getAlarmConfigSelectApi
} from "@/api/alarmConfig";
export function usePage() {
  const form = reactive({
    page: 1,
    perPage: 10,
    code: null,
	name: null,
	isTicket: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const isTicketOption =ref([
  	{
  		id: 1,
  		name: '否'
  	},
  	{
  		id: 2,
  		name: '是'
  	},
  ])
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "alarmBehaveId",
      width: 80
    },
	{
	  label: "报警行为名称",
	  prop: "name",
	},
    {
      label: "报警行为",
      prop: "behaveCode",
    },
    {
    	label: "时间间隔(分钟)",
    	prop: "interval",
    },
    {
    	label: "是否生成工单",
    	prop: "isTicket",
		
		cellRenderer: ({ row }) => (
		  <el-tag size="large" type={row.isTicket ===1?'info':'primary'} effect="light">
		    {row.isTicket ===1?'否':'是'}
		  </el-tag>
		)
    },
	{
		label: "备注",
		prop: "remarks",
	},
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 160
    }
  ];
  function handleSizeChange(val: number) {
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.page = val;
	onSearch()
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getAlarmBehaveListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.code = null;
    form.name = null;
    form.isTicket = null;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		interval: 60
      };
    } else {
      const res = await getAlarmBehaveShowApi({
        alarmBehaveId: row?.alarmBehaveId
      });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline.value = {
        title: "修改",
        alarmBehaveId: row?.alarmBehaveId ?? "",
        code: res?.result?.code ?? "",
        isTicket: res?.result?.isTicket ?? "",
		interval: res?.result?.interval ?? 60,
		name: res?.result?.name ?? "",
		behaveCode: res?.result?.behaveCode.split(",") ?? "",
		remarks: res?.result?.remarks ?? "",
      };
    }
	formInline.value.isTicketOption = isTicketOption.value
	formInline.value.behaveCodeOption = behaveCodeOption.value
    addDialog({
      title: `${title}报警行为信息`,
      props: {
        formInline: formInline
      },
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了报警行为`, {
            type: "success"
          });
          done();
          onSearch();
        }
		
        FormRef.validate(valid => {
          if (valid) {
			let params = {
				name: curData.name,
				behaveCode: curData.behaveCode.toString(),
				interval: curData.interval,
				remarks: curData.remarks,
				isTicket: curData.isTicket,
				alarmBehaveId: curData.alarmBehaveId,
			}
            if (title === "新增") {
              createAlarmBehaveApi(params)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateAlarmBehaveApi(params)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  const behaveCodeOption = ref()
  const getAlarmConfigSelect = async() => {
	  const res = await getAlarmConfigSelectApi()
	  if(res?.code ===200) {
		behaveCodeOption.value = res.result
	  }
  }
  onMounted(async () => {
    onSearch();
	getAlarmConfigSelect()
  });

  function handleDelete(row) {
    delAlarmBehaveApi({ alarmBehaveId: row.alarmBehaveId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
	isTicketOption
  };
}
